package middleware

import (
	"net/http"
	"product-management-system/config"
	"product-management-system/models"
	"product-management-system/utils"
	"strings"

	"github.com/gin-gonic/gin"
)

// JWTAuthMiddleware 验证JWT token的中间件
func JWTAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authorization := c.GetHeader("Authorization")
		if authorization == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "未提供认证token"})
			c.Abort()
			return
		}

		parts := strings.SplitN(authorization, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "认证格式错误"})
			c.Abort()
			return
		}

		claims, err := utils.ValidateJWT(parts[1])
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "无效的token"})
			c.Abort()
			return
		}

		c.Set("username", claims.Username)
		c.Set("role", claims.Role)
		c.Next()
	}
}

// APIKeyAuthMiddleware 验证API key的中间件
func APIKeyAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		apiKey := c.GetHeader("X-API-Key")
		if apiKey == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "未提供API key"})
			c.Abort()
			return
		}

		// 从数据库中验证API key
		var key models.APIKey
		result := config.DB.Where("key = ? AND status = ?", apiKey, "active").First(&key)
		if result.Error != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "无效的API key"})
			c.Abort()
			return
		}

		c.Next()
	}
}